import Limit from '@/components/Limit';
import { doFetch, getFetch } from '@/utils/doFetch';
import { difftime } from '@/utils/time';
import { CloseOutlined } from '@ant-design/icons';
import { useModel } from '@umijs/max';
import { useRequest } from 'ahooks';
import { Avatar, Empty, Popconfirm, Tabs, Tag, theme, Timeline } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import ChangeUser from '../Action/changeuser';
import SvgDot from '../SvgDot';
import { items as itemconfig } from '@/utils/global';
import './index.less';


function Detail(props) {
  const { refresh, data, refreshlist } = props ?? {};

  const { token } = theme.useToken();

  const { colorText, colorPrimary, colorBgFourth, colorOppsites, colorBgContainer } = token;

  const {
    initialState: { currentUser },
  } = useModel('@@initialState');

  const isMine = currentUser?.id === data?.userId;
  const [fileloading, setFileloading] = useState(false);
  const { run, loading, runAsync } = useRequest(
    (params) => {
      return doFetch(params);
    },
    {
      manual: true,
      debounceWait: 400,
      onSuccess: () => {
        refresh();
        refreshlist();
        setFileloading(false);
      },
    },
  );

  return (
    <div
      style={{
        width: '100%',
        overflow: 'hidden',
        color: colorText,
        borderRadius: 12,
        background: colorOppsites,
        padding: "12px 12px 6px 12px",
        marginBottom:12
      }}
    >
      <Limit
        content={data?.remark || '未填写标准'}
        loading={loading}
        onChange={async (val) => {
          await runAsync({
            url: '/item/' + data?.id,
            params: { remark: val },
            method: 'PUT',
          });
        }}
        style={{ borderRadius: 10, marginTop: -10 }}
      />

      <div className='spread' style={{ marginBottom: 16, marginTop: 20 }}>
        <ChangeUser item={data} run={run} notooltip nopopover />
        <div style={{ opacity: 0.5 }}>
          创建于:{difftime(dayjs(), dayjs(data?.createTime))}
        </div>
      </div>
      <div className="columns" style={{opacity:0.7}}>
        <div className='spread'>
          <b>计划开始日期</b>
          <span>
            {data?.planStart ?? '-'}
          </span>
        </div>
        <div className='spread'>
          <b>计划结束日期</b>
          <span>
            {data?.planEnd ?? '-'}
          </span>
        </div>
      </div>

      <div className='columns resets' style={{ margin: '8px 0 0px 0', "--color": colorBgContainer, gap: 8 }}>
        <div className="centerl" style={{ gap: 10, flexWrap: 'wrap' }}>
          {data?.fileList
            ? data?.fileList?.map?.((it, i) => (
              <Tag
                key={it?.uid}
                className='center'
                style={{ maxWidth: 160, marginRight: 0, height: 25 }}
              >
                <a
                  download={it?.name}
                  target={'_blank'}
                  href={it?.url}
                  key={i}
                  rel="noreferrer"
                  title={it?.name}
                >
                  <span style={{ color: colorText, maxWidth: 130, opacity: 0.65 }} className='oneline'>
                    {it?.name}
                  </span>
                </a>
                <Popconfirm
                  title='是否删除该附件？'
                  okText='删除'
                  cancelText='取消'
                  placement='bottom'
                  onConfirm={() => {
                    runAsync({
                      url: '/item/' + data?.id,
                      params: { fileList: data?.fileList?.filter((item) => item?.uid !== it?.uid) },
                      method: 'PUT',
                    });
                  }}
                >
                  <a>
                    <CloseOutlined style={{ marginLeft: 4 }} />
                  </a>
                </Popconfirm>
              </Tag>
            ))
            : '-'}
        </div>
      </div>
    </div>
  );
}


function Actions(props) {
  const { token } = theme.useToken();

  const { colorText, colorBgFourth } = token;
  const { data } = useRequest(
    async () => {
      let res = await getFetch({
        url: '/itemResume',
        params: {
          itemId: props?.data?.id,
        },
      });
      return res?.data?.dataList;
    },
    {
      refreshDeps: [props?.data?.id, props?.activeKey],
    },
  );

  return (
    <div
      style={{
        marginBottom: 12,
        width: '100%',
        overflow: 'hidden',
        color: colorText,
        backgroundColor: colorBgFourth,
        borderRadius: 12,
        width: '100%',
      }}
    >
      <div style={{ overflowX: 'hidden', margin: '0 auto', paddingLeft: 24,paddingTop:30 }}>
        {data?.length > 0 ? (
          <Timeline
            items={data?.map((item, i) => {
              return {
                children: (
                  <div className='columns' style={{ width: '100%', alignItems: "flex-start" }}>
                    <b style={{ marginRight: 10 }}>{item.createUserName}</b>
                    <div style={{ margin: '6px 0', width: "88%" }}>{item.info}</div>
                    <div style={{ color: '#999' }}>{difftime(dayjs(), dayjs(item.createTime))}</div>
                  </div>
                ),
                dot: <Avatar src={item.userHeadUrl} size={'small'}>{item.createUserName?.charAt(0)}</Avatar>,
              };
            })}
          />
        ) : (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={'暂无记录'}
            style={{ marginTop: 36, marginBottom: 24 }}
          />
        )}
      </div>
    </div>
  );
}


function Content(props) {
  const [activeKey, setActiveKey] = useState('content');

  const { token } = theme.useToken();
  const { colorText, colorPrimary, colorBgThird } = token;
  const { data, refresh, refreshlist } = props ?? {};

  //防止修改卡顿
  const [planTime, setPlanTime] = useState(data?.planTime);
  useEffect(() => {
    setPlanTime(data?.planTime)
  }, [data?.planTime]);


  return (
    <div
      style={{
        color: colorText,
      }}
    >
      <Tabs
        style={{ marginTop: -16 }}
        activeKey={activeKey}
        onChange={setActiveKey}
        items={[
          {
            key: 'content',
            label: '任务详情',
            children: <Detail {...props} />,
          },
          {
            key: 'action',
            label: '任务动态',
            children: <Actions {...props} activeKey={activeKey} />,
          },
        ]}
        tabBarExtraContent={
          (
            <div className="centerl" style={{ gap: 4 }}>
              <SvgDot
                style={{ marginRight: 5, marginLeft: 5, flexShrink: 0 }}
                placement="bottomLeft"
                color={itemconfig[data?.status]?.color}
                title={itemconfig[data?.status]?.statusName}
                size={14}
              />
              <b>
                {itemconfig[data?.status]?.statusName}
              </b>
            </div>
          )
        }
      />
    </div>
  );
}

export default Content;
